
package action;

import beans.UserBean;
import db.Forum;
import javax.servlet.http.HttpSession;
import net.sourceforge.stripes.action.ActionBean;
import net.sourceforge.stripes.action.ActionBeanContext;
import net.sourceforge.stripes.action.DefaultHandler;
import net.sourceforge.stripes.action.DontValidate;
import net.sourceforge.stripes.action.ForwardResolution;
import net.sourceforge.stripes.action.Resolution;
import net.sourceforge.stripes.action.UrlBinding;
import net.sourceforge.stripes.validation.Validate;

/**
 * Action for add new forum.
 * @author Tomas CASTA
 */
@UrlBinding("/forumAdd.action")
public class AddForumActionBean implements ActionBean {
    /** session */
    private HttpSession session;
    /** action context */
    private ActionBeanContext context;
    /** msg for errors */
    private String errMsg;
    /** forum name */
    @Validate(required = true)
    private String name;
   /** text of messages */
    @Validate(required = true)
    private String msg;
    /** if user is logged */
    private boolean logged;

    public ActionBeanContext getContext() {
        return context;
    }

    public void setContext(ActionBeanContext context) {
        this.context = context;
    }

    public String getErrMsg() {
        return errMsg;
    }

    public String getMsg() {
        return msg;
    }

    public String getName() {
        return name;
    }

    public void setErrMsg(String errMsg) {
        this.errMsg = errMsg;
    }

    public void setMsg(String msg) {
        this.msg = msg;
    }

    public void setName(String name) {
        this.name = name;
    }

    public HttpSession getSession() {
        return session;
    }

    public void setSession(HttpSession session) {
        this.session = session;
    }

    public boolean isLogged() {
        return logged;
    }

    /**
     * Show form for new forum.
     * @return Resolution.
     */
    @DefaultHandler
    @DontValidate
    public Resolution show() {
        return new ForwardResolution("jsp/addForum.jsp");
    }

    /**
     * Add new forum.
     * @return Resolution
     */
    
    public Resolution add() {
        logged = false;
        /* User is logged */
        if (null != context.getRequest().getSession().getAttribute("user")) {
            logged = true;
            Forum forum = new Forum();

            /* Get user info from session */
            UserBean user = (UserBean) context.getRequest().getSession().getAttribute("user");
            forum.setDb(context.getServletContext());

            /* Add new forum */
            int result = forum.addForum(name, msg, user);

            /* Error, forum with this name already exists */
            if (result != 1) {
                errMsg = "Fórum s názvem " + name + " již existuje.";
                return new ForwardResolution("jsp/addForum.jsp");
            }
        }

        /* User is not logged, show index */
        return new ForwardResolution("/index.action");
    }
}
